<template>
  <div class="app-container">
    <el-container>
      <el-aside width="200px">
        <div class="aside-content">
          <h2>数据分析平台</h2>
          <div class="action-buttons">
            <div class="button-container">
              <el-upload
                class="upload-btn"
                action="http://localhost:3000/api/upload"
                :show-file-list="false"
                accept=".csv"
                :before-upload="beforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError">
                <el-button type="primary">导入数据</el-button>
              </el-upload>
            </div>
            <div class="button-container">
              <el-button type="success" @click="handleExport">导出数据</el-button>
            </div>
            <div class="button-container">
              <el-button type="danger" @click="handleLogout">退出登录</el-button>
            </div>
          </div>
        </div>
      </el-aside>
      <el-main>
        <FilterPanel 
          @filter-change="handleFilterChange" 
          @merge-change="handleMergeChange"
          ref="filterPanel" 
        />
        <DataTable 
          :filters="currentFilters" 
          :merge-schools="mergeSchools"
          ref="dataTable" 
        />
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import * as XLSX from 'xlsx'
import FilterPanel from '../components/FilterPanel.vue'
import DataTable from '../components/DataTable.vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'DashboardView',
  components: {
    FilterPanel,
    DataTable
  },
  setup() {
    /* existing setup code */
    const router = useRouter()
    const dataTable = ref(null)
    const currentFilters = ref({})
    const mergeSchools = ref(false)

    const handleFilterChange = (filters) => {
      currentFilters.value = { ...filters }
    }

    const handleMergeChange = (value) => {
      mergeSchools.value = value
    }

    const beforeUpload = (file) => {
      const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv')
      if (!isCSV) {
        ElMessage.error('只能上传 CSV 文件!')
        return false
      }
      return true
    }

    const handleUploadSuccess = () => {
      ElMessage.success('数据导入成功')
      // 刷新数据表格
      if (dataTable.value) {
        dataTable.value.fetchData({})
      }
    }

    const handleUploadError = () => {
      ElMessage.error('数据导入失败')
    }

    const headerMap = {
      school: '学校',
      competition: '赛项',
      track: '赛道',
      award: '奖项',
      group: '组别',
      province: '省份',
      city: '市区',
      year: '年份',
      session: '届数',
      department: '学院',
      teacher: '指导教师',
      phone: '联系电话',
      organization: '组织名称',
      remarks: '备注'
    }

    const handleExport = async () => {
      if (!dataTable.value?.tableData?.length) {
        ElMessage.warning('没有可导出的数据')
        return
      }

      try {
        const data = dataTable.value.tableData
        // 转换数据，将英文键替换为中文表头
        const exportData = data.map(row => {
          const newRow = {}
          Object.keys(headerMap).forEach(key => {
            newRow[headerMap[key]] = row[key]
          })
          return newRow
        })

        const worksheet = XLSX.utils.json_to_sheet(exportData)
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, worksheet, '竞赛数据')
        
        const date = new Date().toISOString().split('T')[0]
        const fileName = `竞赛数据_${date}.xlsx`
        
        XLSX.writeFile(workbook, fileName)
        ElMessage.success('数据导出成功')
      } catch (error) {
        console.error('Export failed:', error)
        ElMessage.error('数据导出失败')
      }
    }

    const handleLogout = () => {
      localStorage.removeItem('isAuthenticated')
      router.push('/')
      ElMessage.success('已退出登录')
    }

    return {
      dataTable,
      currentFilters,
      handleFilterChange,
      beforeUpload,
      handleUploadSuccess,
      handleUploadError,
      handleExport,
      handleLogout,
      mergeSchools,
      handleMergeChange
    }
  }
}
</script>

<style>
.app-container {
  height: 100vh;
}

.el-container {
  height: 100%;
}

.el-aside {
  background-color: #304156;
  color: #fff;
  box-shadow: 2px 0 6px rgba(0,21,41,.35);
}

.aside-content {
  padding: 20px;
}

.aside-content h2 {
  margin-bottom: 50px;  /* 增加标题底部间距，原来是30px */
  text-align: center;
  color: #fff;
  font-size: 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 0 20px;  /* 可选：添加左右内边距 */
}

.button-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.el-main {
  padding: 20px;
  background-color: #f0f2f5;
}
</style>
